<?php


namespace app\api\controller\v1;


use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\api\service\Token as TokenService;
use app\api\validate\IDMustBePositiveInt;
use app\api\validate\OrderPlace;
use app\api\validate\PagingParameter;
use app\lib\exception\OrderException;

class Order
{
    protected $middleware = [
        'checkExclusiveScope' => ['only' => 'placeOrder'],
        'checkPrimaryScope'=> ['only'=>'getDetail,getSummaryByUser']
    ];

    public function placeOrder()
    {
        (new OrderPlace())->goCheck();
        $products = input('post.products/a');
        $uid = TokenService::getCurrentUid();

        $order = new OrderService();
        $status = $order->place($uid, $products);
        return json($status);
    }

    public function getDetail($id)
    {
        (new IDMustBePositiveInt())->goCheck();
        $orderDetail = OrderModel::find($id);
        if (!$orderDetail) {
            throw new OrderException();
        }
        return $orderDetail->hidden(['user_id', 'delete_time', 'update_time','prepay_id']);
    }

    public function getSummaryByUser($page = 1,$size = 15)
    {
        (new PagingParameter())->goCheck();
        $uid = TokenService::getCurrentUid();
        $pagingOrders = OrderModel::getSummaryByUser($uid,$page,$size);
        if ($pagingOrders->isEmpty()) {
            return [
                'data'=>[],
                'current_page'=>$pagingOrders->currentPage()
            ];
        }
        $data = $pagingOrders->hidden(['snap_items','snap_address','prepay_id','user_id', 'delete_time', 'update_time'])->toArray();
        return json([
            'data'=>$data,
            'current_page'=>$pagingOrders->currentPage()
        ]);
    }
}